<template>
  <div class="sql-formatter-tool">
    <div class="tool-header">
      <h1>SQL格式化</h1>
      <p>格式化SQL语句</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 格式化主体 -->
        <el-col :span="16">
          <div class="formatter-section">
            <!-- SQL输入 -->
            <div class="sql-input">
              <h3>SQL语句输入</h3>
              <div class="input-actions">
                <el-button @click="pasteSQL" size="small">
                  <el-icon><DocumentCopy /></el-icon>
                  粘贴SQL
                </el-button>
                <el-button @click="clearSQL" size="small">
                  清空
                </el-button>
                <el-button @click="loadSample" size="small">
                  加载示例
                </el-button>
              </div>
              <div class="sql-editor">
                <el-input
                  v-model="inputSQL"
                  type="textarea"
                  :rows="12"
                  placeholder="请输入要格式化的SQL语句..."
                  class="sql-textarea"
                />
              </div>
            </div>
            
            <!-- 格式化选项 -->
            <div class="format-options">
              <h3>格式化选项</h3>
              <div class="options-grid">
                <div class="option-group">
                  <label>缩进类型：</label>
                  <el-select v-model="formatOptions.indentType" size="small">
                    <el-option label="空格" value="space" />
                    <el-option label="制表符" value="tab" />
                  </el-select>
                </div>
                <div class="option-group">
                  <label>缩进大小：</label>
                  <el-select v-model="formatOptions.indentSize" size="small">
                    <el-option label="2" :value="2" />
                    <el-option label="4" :value="4" />
                    <el-option label="8" :value="8" />
                  </el-select>
                </div>
                <div class="option-group">
                  <label>关键字大小写：</label>
                  <el-select v-model="formatOptions.keywordCase" size="small">
                    <el-option label="大写" value="upper" />
                    <el-option label="小写" value="lower" />
                    <el-option label="保持原样" value="preserve" />
                  </el-select>
                </div>
                <div class="option-group">
                  <label>函数名大小写：</label>
                  <el-select v-model="formatOptions.functionCase" size="small">
                    <el-option label="大写" value="upper" />
                    <el-option label="小写" value="lower" />
                    <el-option label="保持原样" value="preserve" />
                  </el-select>
                </div>
                <div class="option-group">
                  <label>数据类型大小写：</label>
                  <el-select v-model="formatOptions.dataTypeCase" size="small">
                    <el-option label="大写" value="upper" />
                    <el-option label="小写" value="lower" />
                    <el-option label="保持原样" value="preserve" />
                  </el-select>
                </div>
                <div class="option-group">
                  <label>行长度限制：</label>
                  <el-input-number v-model="formatOptions.lineLength" :min="40" :max="200" size="small" />
                </div>
              </div>
            </div>
            
            <!-- 格式化按钮 -->
            <div class="format-actions">
              <el-button @click="formatSQL" type="primary" size="large" :loading="isFormatting" :disabled="!inputSQL.trim()">
                <el-icon><Edit /></el-icon>
                格式化SQL
              </el-button>
              <el-button @click="copyResult" size="large" :disabled="!formattedSQL">
                <el-icon><DocumentCopy /></el-icon>
                复制结果
              </el-button>
              <el-button @click="downloadResult" size="large" :disabled="!formattedSQL">
                <el-icon><Download /></el-icon>
                下载文件
              </el-button>
            </div>
            
            <!-- 格式化结果 -->
            <div class="format-result" v-if="formattedSQL">
              <h3>格式化结果</h3>
              <div class="result-info">
                <div class="info-item">
                  <span class="info-label">原始行数：</span>
                  <span class="info-value">{{ originalLines }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">格式化后行数：</span>
                  <span class="info-value">{{ formattedLines }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">字符数：</span>
                  <span class="info-value">{{ formattedSQL.length }}</span>
                </div>
              </div>
              <div class="result-editor">
                <el-input
                  v-model="formattedSQL"
                  type="textarea"
                  :rows="12"
                  readonly
                  class="sql-textarea"
                />
              </div>
            </div>
            
            <!-- SQL分析 -->
            <div class="sql-analysis" v-if="sqlAnalysis">
              <h3>SQL分析</h3>
              <div class="analysis-grid">
                <div class="analysis-item">
                  <div class="analysis-label">SQL类型</div>
                  <div class="analysis-value">{{ sqlAnalysis.type }}</div>
                </div>
                <div class="analysis-item">
                  <div class="analysis-label">表数量</div>
                  <div class="analysis-value">{{ sqlAnalysis.tableCount }}</div>
                </div>
                <div class="analysis-item">
                  <div class="analysis-label">字段数量</div>
                  <div class="analysis-value">{{ sqlAnalysis.columnCount }}</div>
                </div>
                <div class="analysis-item">
                  <div class="analysis-label">JOIN数量</div>
                  <div class="analysis-value">{{ sqlAnalysis.joinCount }}</div>
                </div>
                <div class="analysis-item">
                  <div class="analysis-label">子查询数量</div>
                  <div class="analysis-value">{{ sqlAnalysis.subqueryCount }}</div>
                </div>
                <div class="analysis-item">
                  <div class="analysis-label">复杂度</div>
                  <div class="analysis-value" :class="getComplexityClass(sqlAnalysis.complexity)">
                    {{ sqlAnalysis.complexity }}
                  </div>
                </div>
              </div>
              
              <div class="analysis-details">
                <div class="detail-section" v-if="sqlAnalysis.tables.length > 0">
                  <h4>涉及表</h4>
                  <div class="table-list">
                    <el-tag v-for="table in sqlAnalysis.tables" :key="table" size="small">
                      {{ table }}
                    </el-tag>
                  </div>
                </div>
                
                <div class="detail-section" v-if="sqlAnalysis.columns.length > 0">
                  <h4>涉及字段</h4>
                  <div class="column-list">
                    <el-tag v-for="column in sqlAnalysis.columns" :key="column" size="small" type="success">
                      {{ column }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 格式化历史 -->
            <div class="format-history">
              <h3>格式化历史</h3>
              <div class="history-list">
                <div 
                  v-for="(item, index) in formatHistory" 
                  :key="index"
                  class="history-item"
                  @click="loadFromHistory(item)"
                >
                  <div class="history-type">{{ item.type }}</div>
                  <div class="history-info">
                    <span class="history-lines">{{ item.lines }} 行</span>
                    <span class="history-time">{{ item.time }}</span>
                  </div>
                </div>
                <div v-if="formatHistory.length === 0" class="empty-history">
                  暂无格式化历史
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 工具和说明 -->
        <el-col :span="8">
          <div class="tools-section">
            <div class="section-header">
              <h3>SQL示例</h3>
            </div>
            
            <div class="sql-samples">
              <div 
                v-for="sample in sqlSamples" 
                :key="sample.name"
                class="sample-item"
                @click="loadSampleSQL(sample)"
              >
                <div class="sample-name">{{ sample.name }}</div>
                <div class="sample-description">{{ sample.description }}</div>
              </div>
            </div>
          </div>
          
          <div class="help-section">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>使用说明</span>
                </div>
              </template>
              
              <div class="help-content">
                <h4>支持的SQL：</h4>
                <ul>
                  <li><strong>SELECT：</strong> 查询语句</li>
                  <li><strong>INSERT：</strong> 插入语句</li>
                  <li><strong>UPDATE：</strong> 更新语句</li>
                  <li><strong>DELETE：</strong> 删除语句</li>
                  <li><strong>CREATE：</strong> 创建语句</li>
                  <li><strong>ALTER：</strong> 修改语句</li>
                  <li><strong>DROP：</strong> 删除语句</li>
                </ul>
                
                <h4>格式化特性：</h4>
                <ul>
                  <li><strong>关键字格式化：</strong> 自动调整大小写</li>
                  <li><strong>缩进对齐：</strong> 层级结构清晰</li>
                  <li><strong>换行优化：</strong> 长语句自动换行</li>
                  <li><strong>语法分析：</strong> 识别SQL结构</li>
                </ul>
                
                <h4>注意事项：</h4>
                <div class="warning">
                  <p>⚠️ 确保SQL语法正确</p>
                  <p>⚠️ 复杂查询可能需要手动调整</p>
                  <p>⚠️ 格式化会改变代码结构</p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy, Edit, Download } from '@element-plus/icons-vue'

const inputSQL = ref('')
const formattedSQL = ref('')
const isFormatting = ref(false)
const sqlAnalysis = ref(null)
const formatHistory = ref([])

const formatOptions = ref({
  indentType: 'space',
  indentSize: 2,
  keywordCase: 'upper',
  functionCase: 'upper',
  dataTypeCase: 'upper',
  lineLength: 80
})

const sqlSamples = [
  {
    name: '简单查询',
    description: '基本的SELECT语句',
    sql: 'select * from users where age > 18'
  },
  {
    name: '多表连接',
    description: 'JOIN查询示例',
    sql: 'select u.name, p.title from users u join posts p on u.id = p.user_id where u.status = "active"'
  },
  {
    name: '子查询',
    description: '包含子查询的复杂语句',
    sql: 'select name from users where id in (select user_id from orders where amount > 100)'
  },
  {
    name: '聚合查询',
    description: 'GROUP BY和聚合函数',
    sql: 'select department, count(*) as emp_count, avg(salary) as avg_salary from employees group by department having count(*) > 5'
  },
  {
    name: '创建表',
    description: 'CREATE TABLE语句',
    sql: 'create table products (id int primary key auto_increment, name varchar(100) not null, price decimal(10,2), created_at timestamp default current_timestamp)'
  }
]

const originalLines = computed(() => {
  return inputSQL.value ? inputSQL.value.split('\n').length : 0
})

const formattedLines = computed(() => {
  return formattedSQL.value ? formattedSQL.value.split('\n').length : 0
})

const pasteSQL = async () => {
  try {
    const text = await navigator.clipboard.readText()
    inputSQL.value = text
    ElMessage.success('SQL已粘贴')
  } catch (error) {
    ElMessage.error('无法访问剪贴板')
  }
}

const clearSQL = () => {
  inputSQL.value = ''
  formattedSQL.value = ''
  sqlAnalysis.value = null
  ElMessage.info('SQL已清空')
}

const loadSample = () => {
  inputSQL.value = sqlSamples[0].sql
  ElMessage.success('示例SQL已加载')
}

const loadSampleSQL = (sample) => {
  inputSQL.value = sample.sql
  ElMessage.success(`已加载：${sample.name}`)
}

const formatSQL = async () => {
  if (!inputSQL.value.trim()) {
    ElMessage.warning('请输入要格式化的SQL语句')
    return
  }
  
  isFormatting.value = true
  
  try {
    // 模拟格式化过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 简单的SQL格式化逻辑
    let formatted = inputSQL.value.trim()
    
    // 关键字大小写转换
    const keywords = ['SELECT', 'FROM', 'WHERE', 'JOIN', 'LEFT', 'RIGHT', 'INNER', 'OUTER', 'ON', 'GROUP', 'BY', 'HAVING', 'ORDER', 'ASC', 'DESC', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'SET', 'DELETE', 'CREATE', 'TABLE', 'ALTER', 'DROP', 'INDEX', 'PRIMARY', 'KEY', 'FOREIGN', 'REFERENCES', 'NOT', 'NULL', 'DEFAULT', 'AUTO_INCREMENT', 'UNIQUE', 'CHECK', 'CONSTRAINT']
    
    if (formatOptions.value.keywordCase === 'upper') {
      keywords.forEach(keyword => {
        const regex = new RegExp(`\\b${keyword}\\b`, 'gi')
        formatted = formatted.replace(regex, keyword)
      })
    } else if (formatOptions.value.keywordCase === 'lower') {
      keywords.forEach(keyword => {
        const regex = new RegExp(`\\b${keyword}\\b`, 'gi')
        formatted = formatted.replace(regex, keyword.toLowerCase())
      })
    }
    
    // 基本格式化
    formatted = formatted
      .replace(/\s+/g, ' ')
      .replace(/\bSELECT\b/gi, '\nSELECT')
      .replace(/\bFROM\b/gi, '\nFROM')
      .replace(/\bWHERE\b/gi, '\nWHERE')
      .replace(/\bJOIN\b/gi, '\nJOIN')
      .replace(/\bLEFT JOIN\b/gi, '\nLEFT JOIN')
      .replace(/\bRIGHT JOIN\b/gi, '\nRIGHT JOIN')
      .replace(/\bINNER JOIN\b/gi, '\nINNER JOIN')
      .replace(/\bOUTER JOIN\b/gi, '\nOUTER JOIN')
      .replace(/\bON\b/gi, '\n  ON')
      .replace(/\bGROUP BY\b/gi, '\nGROUP BY')
      .replace(/\bHAVING\b/gi, '\nHAVING')
      .replace(/\bORDER BY\b/gi, '\nORDER BY')
      .replace(/\bINSERT INTO\b/gi, '\nINSERT INTO')
      .replace(/\bVALUES\b/gi, '\nVALUES')
      .replace(/\bUPDATE\b/gi, '\nUPDATE')
      .replace(/\bSET\b/gi, '\nSET')
      .replace(/\bDELETE FROM\b/gi, '\nDELETE FROM')
      .replace(/\bCREATE TABLE\b/gi, '\nCREATE TABLE')
      .replace(/\bALTER TABLE\b/gi, '\nALTER TABLE')
      .replace(/\bDROP TABLE\b/gi, '\nDROP TABLE')
      .split('\n')
      .map(line => line.trim())
      .filter(line => line)
      .join('\n')
    
    formattedSQL.value = formatted
    
    // 分析SQL
    analyzeSQL(formatted)
    
    // 添加到历史
    addToHistory()
    
    ElMessage.success('SQL格式化完成')
    
  } catch (error) {
    ElMessage.error('格式化失败：' + error.message)
  } finally {
    isFormatting.value = false
  }
}

const analyzeSQL = (sql) => {
  const analysis = {
    type: 'UNKNOWN',
    tableCount: 0,
    columnCount: 0,
    joinCount: 0,
    subqueryCount: 0,
    complexity: 'SIMPLE',
    tables: [],
    columns: []
  }
  
  // 检测SQL类型
  if (sql.toUpperCase().includes('SELECT')) analysis.type = 'SELECT'
  else if (sql.toUpperCase().includes('INSERT')) analysis.type = 'INSERT'
  else if (sql.toUpperCase().includes('UPDATE')) analysis.type = 'UPDATE'
  else if (sql.toUpperCase().includes('DELETE')) analysis.type = 'DELETE'
  else if (sql.toUpperCase().includes('CREATE')) analysis.type = 'CREATE'
  else if (sql.toUpperCase().includes('ALTER')) analysis.type = 'ALTER'
  else if (sql.toUpperCase().includes('DROP')) analysis.type = 'DROP'
  
  // 统计表数量
  const tableMatches = sql.match(/\bFROM\s+(\w+)/gi) || []
  analysis.tableCount = tableMatches.length
  
  // 统计JOIN数量
  const joinMatches = sql.match(/\bJOIN\b/gi) || []
  analysis.joinCount = joinMatches.length
  
  // 统计子查询数量
  const subqueryMatches = sql.match(/\([^)]*SELECT[^)]*\)/gi) || []
  analysis.subqueryCount = subqueryMatches.length
  
  // 计算复杂度
  if (analysis.joinCount > 3 || analysis.subqueryCount > 2) {
    analysis.complexity = 'COMPLEX'
  } else if (analysis.joinCount > 1 || analysis.subqueryCount > 0) {
    analysis.complexity = 'MEDIUM'
  } else {
    analysis.complexity = 'SIMPLE'
  }
  
  sqlAnalysis.value = analysis
}

const getComplexityClass = (complexity) => {
  switch (complexity) {
    case 'SIMPLE': return 'success'
    case 'MEDIUM': return 'warning'
    case 'COMPLEX': return 'danger'
    default: return 'info'
  }
}

const copyResult = async () => {
  try {
    await navigator.clipboard.writeText(formattedSQL.value)
    ElMessage.success('结果已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const downloadResult = () => {
  const filename = 'formatted_query.sql'
  
  const blob = new Blob([formattedSQL.value], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('文件已下载')
}

const addToHistory = () => {
  const historyItem = {
    type: sqlAnalysis.value?.type || 'UNKNOWN',
    lines: formattedLines.value,
    time: new Date().toLocaleString('zh-CN')
  }
  
  formatHistory.value.unshift(historyItem)
  
  // 限制历史记录数量
  if (formatHistory.value.length > 20) {
    formatHistory.value = formatHistory.value.slice(0, 20)
  }
}

const loadFromHistory = (item) => {
  ElMessage.success(`已加载：${item.type} 格式化历史`)
}
</script>

<style scoped>
.sql-formatter-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.formatter-section,
.tools-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.sql-input,
.format-options,
.format-actions,
.format-result,
.sql-analysis,
.format-history {
  margin-bottom: 30px;
}

.sql-input h3,
.format-options h3,
.format-result h3,
.sql-analysis h3,
.format-history h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.3rem;
}

.input-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.sql-editor {
  position: relative;
}

.sql-textarea {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.option-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-group label {
  font-weight: 500;
  color: #666;
}

.format-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.result-info {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.info-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 5px;
}

.info-value {
  font-size: 1.1rem;
  font-weight: bold;
  color: #333;
}

.result-editor {
  position: relative;
}

.analysis-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.analysis-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  border: 1px solid #e9ecef;
}

.analysis-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 5px;
}

.analysis-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
}

.analysis-value.success {
  color: #28a745;
}

.analysis-value.warning {
  color: #ffc107;
}

.analysis-value.danger {
  color: #dc3545;
}

.analysis-details {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e9ecef;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.detail-section h4 {
  color: #333;
  margin-bottom: 10px;
  font-size: 1.1rem;
}

.table-list,
.column-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.history-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
}

.history-type {
  font-size: 1rem;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.history-info {
  display: flex;
  gap: 15px;
  font-size: 0.9rem;
  color: #666;
}

.history-lines {
  color: #667eea;
  font-weight: 500;
}

.history-time {
  color: #999;
}

.empty-history {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-style: italic;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.sql-samples {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.sample-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.sample-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.sample-name {
  font-size: 1rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.sample-description {
  font-size: 0.9rem;
  color: #666;
}

.help-section {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.help-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.help-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.help-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .options-grid {
    grid-template-columns: 1fr;
  }
  
  .format-actions {
    flex-direction: column;
  }
  
  .result-info {
    flex-direction: column;
    gap: 10px;
  }
  
  .analysis-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .history-info {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
